package parse;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;

import data.Game;
import data.GameList;
import data.Player;
import data.TournamentList;

public class GameParser {
	
private String fileName = null;

	private TournamentList tournamentList = null;
	private static final int PLAYERS = 3;
	
	public GameParser (String aFileName, TournamentList aList){
		fileName = aFileName;
		tournamentList = aList;
	}		
	
	public GameList parse(){
		GameList res = new GameList();
		
		FileInputStream fis = null;
		BufferedReader reader = null;
		String line;
		
		try{
			fis = new FileInputStream(fileName);
			reader = new BufferedReader(new InputStreamReader
					(fis, Charset.forName("UTF-8")));
			
			while ((line = reader.readLine()) != null) {
				Game g = parseLine (line);
				if (g != null){
					res.addGame (g);
				}				
			}
			reader.close();
		} catch (IOException io){			
			reader = null;
			fis = null;
			io.printStackTrace ();
		}								
		return res;
	}
	
	private Game parseLine(String line){
		String[] tmp = line.split(" ");		
		ArrayList<Player> gamers = new ArrayList<Player>(); 
		ArrayList<Double> results = new ArrayList<Double>();
					
		if (tmp.length != PLAYERS*2){
			return null;
		}
		for (int i = 0; i < PLAYERS; i++){
			Player gamer = tournamentList.find (tmp[i]);
			gamer.addPoints (Double.parseDouble (tmp[i+PLAYERS]));
			int q = roundInc(i,PLAYERS);
			gamer.addToBan (tournamentList.find(tmp[q]));
			q = roundInc(q,PLAYERS);
			gamer.addToBan (tournamentList.find(tmp[q]));
			
			gamers.add(gamer);
			results.add(Double.parseDouble (tmp[i+PLAYERS]));
		}		
		return new Game(gamers.toArray (new Player[0]),
				results.toArray (new Double[0]));
	}
	
	private int roundInc(int value, int max){
		int min = 0;
		if (value < 0){
			return 0;
		}
		if (value > max){
			return 0;
		}
		value ++;
		if (value >= max){
			return 0;
		}
		return value;
	}
	

}
